package foolcat.tools;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.util.Log;

public class WordList {
	public final static String DICT_PATH = "/sdcard/foolcat/IBTWords/dict";
	public final static String SOUND_FILE = DICT_PATH + "/sound.zip";
	
	public File tempMp3;
	public boolean playing = false;

	
	public String[] getBooksFromSD() {
    	String tmp = "";
    	
    	File f = new File(DICT_PATH);
    	File[] flist = f.listFiles();
    	for (int i = 0; i < flist.length; i++) {
    		if (flist[i].isDirectory()) {
    			tmp += "#" + flist[i].getName();
    		}
    	}
    	return tmp.substring(1).split("#");
    }
	
	public int getBookListCount(String bookname) {
    	File f = new File(DICT_PATH + "/" + bookname);
    	File[] flist = f.listFiles();
    	return flist.length;
    }
    
	public ArrayList<String> getWordFromList(String bookname, int listnum) {
		ArrayList<String> al = new ArrayList<String>();
		String line;
		try {
			File f = new File(DICT_PATH + "/" + bookname + "/list" + listnum + ".txt");
			FileInputStream fileIS = new FileInputStream(f);
		    BufferedReader br = new BufferedReader(new InputStreamReader(fileIS,"GBK"));
		    while ((line = br.readLine()) != null) {
		    	al.add(line);
		    }
		} catch (IOException e) {
			Log.e(this.getClass().getName(), e.getMessage());
		}
		return al;
	}
	
	public byte[] readFromZipFile(String entryName) {
		byte[] b = null;
		ZipFile zip = null;
		BufferedInputStream bis = null;
		ByteArrayOutputStream baos = null;
		
		try {
			zip = new ZipFile(new File(SOUND_FILE),ZipFile.OPEN_READ);
			ZipEntry ze = zip.getEntry(entryName);
			if (ze == null) return b;
//			Enumeration<? extends ZipEntry> zes = zip.entries();
//			while (zes.hasMoreElements()) {
//				ze = zes.nextElement();
//				Log.d(this.getClass().getName(), "name1=["+ze.getName()+"]");
//				Log.d(this.getClass().getName(), "name2=["+entryName+"]");
//				if (entryName.equals(ze.getName())) break;
//			}
			Log.d(this.getClass().getName(), "name="+ze.getName());
			bis = new BufferedInputStream(zip.getInputStream(ze));

			baos = new ByteArrayOutputStream();
	        byte[] buffer = new byte[1024];
	        int count;
	        while ((count = bis.read(buffer)) != -1) {
	            baos.write(buffer, 0, count);
	        }
	        b = baos.toByteArray();
		} catch (IOException e) {
			Log.e(this.getClass().getName(), e.getMessage());
		} finally {
			try{
		        baos.close();
		        bis.close();
		        zip.close();
			}catch(Exception e){}
		}
		return b;
	}

	public void playMp3(MediaPlayer mediaPlayer, File cacheDir, String fname) {
	    try {
	        // create temp file that will hold byte array
	        tempMp3 = File.createTempFile("ibttmpsound", "mp3", cacheDir);
	        tempMp3.deleteOnExit();
	        FileOutputStream fos = new FileOutputStream(tempMp3);
	        byte[] buf = readFromZipFile(fname + ".mp3"); 
	        if (buf == null) {
	        	tempMp3.delete();
	        	Log.w(this.getClass().getName(), "Can't find " + fname + ".mp3 from zip");
	        	return;
	        }
	        fos.write(buf);
	        fos.close();


	        FileInputStream fis = new FileInputStream(tempMp3);
	        mediaPlayer.reset();
	        mediaPlayer.setDataSource(fis.getFD());
	        mediaPlayer.prepare();
	        mediaPlayer.start();
	        playing = true;
	        mediaPlayer.setOnCompletionListener(new OnCompletionListener(){
				public void onCompletion(MediaPlayer arg0) {
					// TODO Auto-generated method stub
					tempMp3.delete();
					playing = false;
				}
	        	
	        });
	        mediaPlayer.setOnErrorListener(new OnErrorListener(){

				public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
					// TODO Auto-generated method stub
					playing = true;
					Log.w(this.getClass().getName(), "MediaPlayer Error");
					return false;
				}
	        	
	        });
	        
	    } catch (IOException ex) {
	        ex.printStackTrace();
	        tempMp3.delete();
	    }
	}	
}
